//
//  EditImage.m
//  MultiViewDemo
//
//  Created by Ngoc on 4/30/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "EditImageController.h"
#import "SwitchViewController.h"
#import "CoordinatingController.h"
#import "FilterView.h"
#define ZOOM_STEP 1.5
@implementation EditImageController
@synthesize imageView=imageView_;
@synthesize parentController;
@synthesize btnSave;
@synthesize menuList,popoverController,undoBarBtnItem,redoBarBtnItem,bottomToolbar,okBarBtnItem,cancelBarBtnItem;
@synthesize imageScrollView;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}
// From other view
-(void) setInputData:(UIImage *)image
{
    if(nil!= imageView_) [imageView_ removeFromSuperview];
    imageView_ = [[UIImageView alloc]initWithImage:image];
    [self imageViewSetUp];

    [self homeViewPrepare];
}
-(void) homeViewPrepare
{
    // hide OK cancel button
    //[self showOrHideOkCancelBarButtonItem:YES];
    // show undo redo button
    //[self showOrHideUndoRedoBarButtonItem:NO];
    
}
-(void) showOrHideOkCancelBarButtonItem:(BOOL)hide
{
    @try {
        switch (hide) {
            case YES:
            {
                // hide ok cancel bar item button
                if(nil != self.okBarBtnItem || nil!=self.cancelBarBtnItem)
                {
                    NSMutableArray *itemsToolbar = [[bottomToolbar items] mutableCopy];
                    if(nil!= self.okBarBtnItem)
                    {
                        [itemsToolbar insertObject:self.okBarBtnItem atIndex:0];
                    }
                    if(nil!=self.cancelBarBtnItem)
                    {
                        [itemsToolbar insertObject:self.cancelBarBtnItem atIndex:4];
                    }
                    [bottomToolbar setItems:itemsToolbar animated:YES];
                    [itemsToolbar release];
                }
                break;
            }

            case NO:
            {
                if(nil == self.okBarBtnItem || nil== self.cancelBarBtnItem)
                {
                if(nil == self.okBarBtnItem)
                {
                    self.okBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"todo.png"] style:UIBarButtonItemStyleBordered target:self action:nil];
                    self.okBarBtnItem.width = 40;
                }
                if(nil== self.cancelBarBtnItem)
                {
                    self.cancelBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"delete.png"] style:UIBarButtonItemStyleBordered target:self action:nil];
                    self.cancelBarBtnItem.width = 40;   
                    
                }
                NSMutableArray *itemsToolbar = [[bottomToolbar items] mutableCopy];
                
                [itemsToolbar insertObject:self.okBarBtnItem atIndex:0];
                [itemsToolbar insertObject:self.cancelBarBtnItem atIndex:4];
                [bottomToolbar setItems:itemsToolbar animated:YES];
                [itemsToolbar release];
                }
                break;
            }
        }
    }
    @catch (NSException *exception) {
        [Util showDebugMessageBox:[exception name] description:[exception description]];
    }

}
// Show or hide bottom toolbar item
-(void) showOrHideUndoRedoBarButtonItem:(BOOL)hide
{
    @try
    {
    switch (hide) {
        case YES:
        {
            // hide undo redo bar item button
            if(nil != self.undoBarBtnItem || nil!=self.redoBarBtnItem)
            {
                NSMutableArray *itemsToolbar = [[bottomToolbar items] mutableCopy];
                if(nil!= self.undoBarBtnItem)
                {
                 [itemsToolbar insertObject:self.undoBarBtnItem atIndex:0];
                }
                if(nil!=self.redoBarBtnItem)
                {
                 [itemsToolbar insertObject:self.redoBarBtnItem atIndex:4];
                }
                [bottomToolbar setItems:itemsToolbar animated:YES];
                [itemsToolbar release];
            }
           // self.btnRedo.enabled = NO;
            break;
        }
        // show undo redo bar item button
        case NO:
        {
            if(nil == self.undoBarBtnItem || nil == self.redoBarBtnItem)
            {
            if(nil == self.undoBarBtnItem)
            {
                self.undoBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"undo.png"] style:UIBarButtonItemStyleBordered target:self action:nil];
               // self.undoBarBtnItem = [[UIBarButtonItem alloc]initWithTitle:@"Undo" style:UIBarButtonItemStyleBordered target:self action:nil];
                self.undoBarBtnItem.width = 40;
            }
            if(nil== self.redoBarBtnItem)
            {
                self.redoBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"redo.png"] style:UIBarButtonItemStyleBordered target:self action:nil];
                
                //self.redoBarBtnItem = [[UIBarButtonItem alloc]initWithTitle:@"Redo" style:UIBarButtonItemStyleBordered target:self action:nil];
                self.redoBarBtnItem.width = 40;   
            
            }
            NSMutableArray *itemsToolbar = [[bottomToolbar items] mutableCopy];
            
            [itemsToolbar insertObject:self.undoBarBtnItem atIndex:0];
            [itemsToolbar insertObject:self.redoBarBtnItem atIndex:4];
            [bottomToolbar setItems:itemsToolbar animated:YES];
            [itemsToolbar release];
            }
            break;
        }
    }
    }
    @catch(NSException *ex)
    {
    
        [Util showDebugMessageBox:[ex name] description:[ex description]];
    }
}
// Show action menu
-(void) showMenu:(Menu)menu anchorRect:(CGRect)locationRect withSize:(CGSize)size withArrowDirection:(UIPopoverArrowDirection)direction
{
    NSArray *array;
    
    BOOL shouldShowNewPopover = TRUE;	
    
    switch (menu) {
        case None:
        {
            return;
            break;
        }
        case Edit:
        {
            array = [[NSArray alloc] initWithObjects:@"Crop", @"Rotate",
                              @"Straighten",@"Flip",@"Draw",nil];
            currentMenu = Edit;
            break;
        }
//        case Draw:
//        {
//            array = [[NSArray alloc] initWithObjects:@"Free", @"Line",@"Rectangle",
//                     @"Arc",@"Circle",nil];
//            currentMenu = Draw;
//            break;
//        }
        case Filter:
        {
            array = [[NSArray alloc] initWithObjects:@"Tint Red", @"Greyscale", @"Pixelate", @"Brightness", @"Saturation", @"Hue", @"Thermal", @"Snow Fuzz", @"Blur", @"Find Edges", @"Emboss", @"Sharpen", @"Tilt Shift",nil];
            currentMenu = Filter;
            break;
        }
        case Border:
        {
            array = [[NSArray alloc] initWithObjects:@"Border 1", @"Border 2",@" Border 3",
                     @"Boder 4",nil];
            currentMenu = Border;
            break;
        }
        case Home:
        {
            array = [[NSArray alloc] initWithObjects:@"Home",@"Save", @"Save & select other",
                     @"Save & Exit",nil];
            currentMenu = Home;
            break;
        }
  
        }
    self.menuList = array;
       
    if (self.popoverController) {
        [self.popoverController dismissPopoverAnimated:YES];
        self.popoverController = nil;
    } 
    
    if (shouldShowNewPopover) {
        
        UIViewController *contentViewController = [[GeMenu alloc] initWithStyle:UITableViewStylePlain andWithSize:size addTarget:self];
        
        ((GeMenu*)contentViewController).listMenu = menuList;
        
        self.popoverController = [[[WEPopoverController alloc] initWithContentViewController:contentViewController] autorelease];
        
        [self.popoverController presentPopoverFromRect:locationRect 
                                                inView:self.view 
                              permittedArrowDirections:direction
                                              animated:YES];
        ((GeMenu*)contentViewController).popoverController = self.popoverController;
        [contentViewController release];
    }
}

-(IBAction) showEditMenu:(id) sender
{
    CGSize size = CGSizeMake(130, 4*44-1);
    CGRect anchorRect = CGRectMake(30, 0, 40,40);
    
    [self showMenu:Edit anchorRect:anchorRect withSize:size withArrowDirection:UIPopoverArrowDirectionUp];
}
//-(IBAction) showDrawMenu:(id)sender
//{
//    CGSize size = CGSizeMake(130, 4*44-1);
//    CGRect anchorRect = CGRectMake(60, 0, 40,40);
//    
////    [self showMenu:Draw anchorRect:anchorRect withSize:size withArrowDirection:UIPopoverArrowDirectionUp];
//}
-(IBAction) showFilterMenu:(id)sender
{
    CGSize size = CGSizeMake(160, 4*44-1);
    CGRect anchorRect = CGRectMake(60, 0, 40,40);//(105, 0, 40,40);
    
    [self showMenu:Filter anchorRect:anchorRect withSize:size withArrowDirection:UIPopoverArrowDirectionUp];
}
-(IBAction) showBorderMenu:(id)sender
{
    CGSize size = CGSizeMake(130, 4*44-1);
    CGRect anchorRect = CGRectMake(105, 0, 40,40);//(150, 0, 40,40);
    
    [self showMenu:Border anchorRect:anchorRect withSize:size withArrowDirection:UIPopoverArrowDirectionUp];
}
-(IBAction) showHomeMenu:(id) sender
{
    CGSize size = CGSizeMake(230, 3*44-1);
    CGRect anchorRect = CGRectMake(248, 0, 40,40);
    
    [self showMenu:Home anchorRect:anchorRect withSize:size withArrowDirection:UIPopoverArrowDirectionUp];
}
-(void) returnParentView
{

        [[SwitchViewController sharedInstance] switchView:self toView:[CoordinatingController sharedInstance].startViewController];

}


-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event    
{
//    NSInteger tapNum = [[touches anyObject] tapCount];
//    
//    if(1==tapNum && self.popoverController)
//    {
//        [self.popoverController dismissPopoverAnimated:YES];
//        self.popoverController = nil;
//    }
    
}


-(void) TableViewCellSelectedHandler:(NSInteger)row cellText:(NSString *)cellText
{
    
    switch (currentMenu)
    {
        case Edit:
        {
            switch (row) {
                case 0:
                {

                }
                case 4:
                {
                    [[SwitchViewController sharedInstance]switchView:self toView:[CoordinatingController sharedInstance].canvasViewController];
                        [[CoordinatingController sharedInstance].canvasViewController setInputData:imageView_.image];
                }
            }
            break;
        }   
        case Filter:
        {
            FilterAlgorithm filter;
            switch(row)
            {
                case 0:
                {
                    filter= TintRed;
                    break;
                }
                case 1:
                {
                    filter= Greyscale;
                    break;
                }
                case 2:
                {
                    filter= Pixelate;
                    break;
                }
                case 3:
                {
                    filter= Brightness;
                    break;
                }
                case 4:
                {
                    filter= Saturation;
                    break;
                }
                case 5:
                {
                    filter= Hue;
                    break;
                }
                case 6:
                {
                    filter= Thermal;
                    break;
                }
                case 7:
                {
                    filter= SnowFuzz;
                    break;
                }
                case 8:
                {
                    filter= Blur;
                    break;
                }
                case 9:
                {
                    filter= FindEdges;
                    break;
                }
                case 10:
                {
                    filter= Emboss;
                    break;
                }
                case 11:
                {
                    filter= Sharpen;
                    break;
                }
                case 12:
                {
                    filter= TiltShift;
                    break;
                }
                
            }
            [[SwitchViewController sharedInstance]switchView:self toView:[[FilterView alloc]initWithFilter:filter originalImage:imageView_.image returnView:self]];
            
            break;
        }
        case Border:
        {
            break;
        }
        case None:
        {
            break;
        }
        case Home:
        {
            switch (row) {
                    // Home
                case 0:
                {
                    [self returnParentView];
                    break;
                }
            }
            break;
        }

    }
}
static EditImageController *sharedEditImageController= nil;
+(EditImageController*) sharedInstance
{
    if(nil == sharedEditImageController)
    {
        sharedEditImageController = [[EditImageController alloc]init];
    }
    return sharedEditImageController;
}
-(void) oneFingerOneTapHandler
{
    if(self.popoverController)
    {
        [self.popoverController dismissPopoverAnimated:YES];
        self.popoverController = nil;
    }
}
-(void) longPressHandler
{
    showToolBar = !showToolBar;
    
    if(showToolBar)
    {
        self.bottomToolbar.hidden = NO;   
    }
    else self.bottomToolbar.hidden = YES;
}

- (void)dealloc
{
    self.menuList = nil;
    [undoBarBtnItem release];
    [redoBarBtnItem release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    if(self.parentController !=nil) [ self.parentController release];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
   // imageView_ = [[UIImageView alloc]init];
    UITapGestureRecognizer *oneFingerOneTap = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(oneFingerOneTapHandler)] autorelease];
    [oneFingerOneTap setNumberOfTapsRequired:1];
    [oneFingerOneTap setNumberOfTouchesRequired:1];
    [self.imageScrollView addGestureRecognizer:oneFingerOneTap];
    
    UILongPressGestureRecognizer *longPress  = [[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressHandler)]autorelease];
    [longPress setNumberOfTapsRequired:1];
    [longPress setNumberOfTouchesRequired:1];
    [self.imageScrollView addGestureRecognizer:longPress];
    
    currentMenu = None;
    showToolBar = NO;
    
    imageScrollView.bouncesZoom = YES;
    imageScrollView.delegate = self;
    imageScrollView.clipsToBounds = YES;
   // [self imageViewSetUp];
    
    [super viewDidLoad];
}
-(void) imageViewSetUp
{

    
    imageView_.userInteractionEnabled = YES;
    imageView_.autoresizingMask = ( UIViewAutoresizingFlexibleWidth );
    [imageScrollView addSubview:imageView_];
    
    
    
    // add gesture recognizers to the image view
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleDoubleTap:)];
    UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerTap:)];
    
    [doubleTap setNumberOfTapsRequired:2];
    [twoFingerTap setNumberOfTouchesRequired:2];
    
    [imageView_ addGestureRecognizer:singleTap];
    [imageView_ addGestureRecognizer:doubleTap];
    [imageView_ addGestureRecognizer:twoFingerTap];
    
    [singleTap release];
    [doubleTap release];
    [twoFingerTap release];
    // calculate minimum scale to perfectly fit image width, and begin at that scale
    float minimumScale = [imageScrollView frame].size.width  / [imageView_ frame].size.width;
    //imageScrollView.maximumZoomScale = 1.0;
    imageScrollView.minimumZoomScale = minimumScale;
    imageScrollView.zoomScale = minimumScale;
    imageScrollView.contentSize = [imageView_ frame].size;
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return imageView_;
}
- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer {
    // single tap does nothing for now
    if(self.popoverController)
    {
        [self.popoverController dismissPopoverAnimated:YES];
        self.popoverController = nil;
    }
}

- (void)handleDoubleTap:(UIGestureRecognizer *)gestureRecognizer {
    // zoom in
    float newScale = [imageScrollView zoomScale] * ZOOM_STEP;
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
    [imageScrollView zoomToRect:zoomRect animated:YES];
}

- (void)handleTwoFingerTap:(UIGestureRecognizer *)gestureRecognizer {
    // two-finger tap zooms out
    float newScale = [imageScrollView zoomScale] / ZOOM_STEP;
    CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
    [imageScrollView zoomToRect:zoomRect animated:YES];
}

#pragma mark Utility methods

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center {
    
    CGRect zoomRect;
    
    // the zoom rect is in the content view's coordinates. 
    //    At a zoom scale of 1.0, it would be the size of the imageScrollView's bounds.
    //    As the zoom scale decreases, so more content is visible, the size of the rect grows.
    zoomRect.size.height = [imageScrollView frame].size.height / scale;
    zoomRect.size.width  = [imageScrollView frame].size.width  / scale;
    
    // choose an origin so as to get the right center.
    zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);
    
    return zoomRect;
}

- (void)viewDidUnload
{
    [menuList release];
    [parentController release];
    [self.imageView release];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}
@end
